package com.lagou.server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();

        return absolutePath.replaceAll("\\\\","/") + path;
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0){
            count = fileInputStream.available();
        }

        int resourceSize = count;

        //输入http请求头,然后再输出具体内容
        outputStream.write(HttpProtocalUtil.getHttpHeader200(resourceSize).getBytes());

        //读取内容输出
        long written = 0;//已经读取的内容长度
        int byteSize = 1024;//计划每次缓冲的长度
        byte[] bytes = null;

        while (written < resourceSize){
            if(written + byteSize > resourceSize){
                byteSize = (int)(resourceSize - written);
            }
            bytes = new byte[byteSize];
            int read = fileInputStream.read(bytes);
            written += read;

            outputStream.write(bytes);
            outputStream.flush();
        }
    }
}
